const express = require('express')
const router = express.Router();

module.exports = router

const db = require('../db')
const { formatData } = require('../utils')

// /POST /api/user/reg
router.post('/reg', async (req, res) => {
    const { username, password } = req.body;
    console.log('username',req.body)
    // 数据库操作
    let sql = `insert into userlist(username,password) values('${username}','${password}')`
    const data = await db.query(sql)
    res.send(formatData())
})
    

router.get('/login', async (req, res) => {
    // req.query
    const {username,password} = req.query;
    let sql = `select * from userlist where username='${username}' and password='${password}'`
    const data = await db.query(sql)
    if(data.length>0){
        res.send(formatData.success(data[0]))
    }else{
        res.send(formatData.fail())
    }

})

// GET /api/user/list   获取用户列表
router.get('/list', async (req, res) => {

    // 数据库操作
    let sql = `select * from users`
    const data = await db.query(sql)
    res.send(formatData({data}))
})
// GET /api/user/check
router.get('/check', async (req,res)=>{
     // 接收前端传入数据
     const {username} = req.query;
     // 检测用户名是否存在，其实就是查询数据库中是否有相同的用户名
     let sql = `select id from userlist where username ='${username}'`
     const data = await db.query(sql)
       if(data.length > 0){
            res.send(formatData.fail())
       }else {
            res.send(formatData({data}))
       }
    })